package ling.learn.template;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.PropertyConfigurator;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;

public class CodeGen {
  private Configuration cfg;

  public CodeGen() {
    this("resource\\template");
  }

  public CodeGen(String templatePath) {
    PropertyConfigurator.configure("resource\\log4j.properties");
    // Logger freemarkerLogger = Logger.getLogger("freemarker.template");
    cfg = new Configuration(new Version("2.3.34"));
    try {
      cfg.setDirectoryForTemplateLoading(new File(templatePath));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void execute(String genFilePath, String templateName, Object dataModel) {
    try {
      Template template = cfg.getTemplate(templateName, "UTF-8");
      StringWriter out = new StringWriter();

      template.process(dataModel, out);

      FileUtils.write(new File(genFilePath), out.getBuffer().toString(), Charset.forName("UTF-8"));

    } catch (TemplateException | IOException e) {
      e.printStackTrace();
    }
  }
}
